﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ParboiledSharp.lang.roboline.context
{
    class VariableManager
    {
        protected List<VariableScope> scopesStack;

        public VariableManager() {
            scopesStack = new List<VariableScope>();
        }

        protected VariableScope getVarScope(int level)
        {
            return scopesStack[scopesStack.Count - 1 - level];
        }

        public VariableScope getGlobalScope() {
            return scopesStack[0];
        }

        protected int ScopesCount
        {
            get { return scopesStack.Count; }
        }

        public void AddScope()
        {
            scopesStack.Add(new VariableScope());
        }

        public void removeScope()
        {
            scopesStack.RemoveAt(scopesStack.Count - 1);
        }

        private Variable SearchVariable(string varName)
        {
            for (int i = 0; i < ScopesCount; i++)
            {
                Variable var = getVarScope(i)[varName];
                if (var != null) return var;
            }

            return null;
        }

        public bool varExists(string varName) {
            return SearchVariable(varName) != null;
        }

        public Variable this[string varName]{
            get { return SearchVariable(varName); }
        }
    }


    class VariableScope
    {
        Dictionary<string, Variable> dict;

        public VariableScope()
        {
            dict = new Dictionary<string, Variable>(20);
        }

        public Variable this[String variableName]
        {
            get { return dict[variableName]; }
            set { dict.Add(variableName, value); }
        }

        public int Count
        {
            get { return dict.Count; }
        }

        public void Clear()
        {
            dict.Clear();
        }
    }
}
